package com.application.chiettinhdienluc.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.DanhMucVatTuAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.VatTuDataSource;
import com.application.chiettinhdienluc.dialog.ConfirmDialog;
import com.application.chiettinhdienluc.model.VattuModel;
import com.application.chiettinhdienluc.rsclient.DataConnDetector;
import com.application.chiettinhdienluc.rsclient.RsGetClient;
import com.application.chiettinhdienluc.utils.Utils;

public class DanhMucVatTuActivity extends SherlockFragmentActivity implements
		android.view.View.OnClickListener {

	private Resources res;
	private ListView chiettinhListView;
	DanhMucVatTuAdapter dataAdapter;

	private EditText edt_filter_vattu_list;
	private TextView tvfilter_vattu_result_count;
	private TextWatcher textChangeListener = null;
	private ArrayList<VattuModel> listvattuModel = new ArrayList<VattuModel>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		
		setContentView(R.layout.danh_muc_vat_tu_listview);
		res = getResources();

		ActionBar actionbar = getSupportActionBar();

		if (actionbar != null) {
			actionbar
					.setTitle(res.getString(R.string.str_title_viewlist_vattu));
			actionbar.setDisplayHomeAsUpEnabled(true);
			actionbar.setDisplayShowHomeEnabled(true);

		}

		edt_filter_vattu_list = (EditText) findViewById(R.id.edt_filter_vattu_list);
		tvfilter_vattu_result_count = (TextView) findViewById(R.id.tvfilter_vattu_result_count);
		textChangeListener = new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapter.getFilter().filter(s, new Filter.FilterListener() {
					@Override
					public void onFilterComplete(int count) {
						tvfilter_vattu_result_count.setText(String.format(
								res.getString(R.string.str_filter_result_count),
								count));
					}
				});
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		};

		edt_filter_vattu_list.addTextChangedListener(textChangeListener);

		chiettinhListView = (ListView) findViewById(R.id.danh_muc_vat_tu_listview);
		dataAdapter = new DanhMucVatTuAdapter(DanhMucVatTuActivity.this,
				listvattuModel);
		chiettinhListView.setAdapter(dataAdapter);
		loadVattu();
		tvfilter_vattu_result_count.setText(String.format(
				res.getString(R.string.str_filter_result_count),
				listvattuModel.size()));
	}

	private void loadVattu() {
		if (listvattuModel != null)
			listvattuModel.clear();

		VatTuDataSource dataSource = new VatTuDataSource();
		listvattuModel = dataSource.loadVattu();
		dataAdapter.setItemList(listvattuModel);
		dataAdapter.notifyDataSetChanged();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
		case android.R.id.home:
			if (checkDataChanged()) {
				// show dialog to alert users
				showDialogOK();
			} else {
				finish();
			}
			break;
		case ID_ACTION_SAVE:
			saveDanhMucVatTu();
			GlobalData.isDone = true;
			Utils.showMess(res.getString(R.string.str_save_danhmuc_success));
			break;
		case ID_ACTION_DOWNLOAD:

			DataConnDetector detector = new DataConnDetector(
					MainApplication.getAppContext());
			if (detector.isConnectingToInternet()) {
				getDanhMucVatTu();
			} else {
				Toast.makeText(MainApplication.getAppContext(),
						R.string.no_connection_message, Toast.LENGTH_SHORT)
						.show();

			}

			break;

		}
		return super.onOptionsItemSelected(item);
	}

	private final int OPTIONMENU_MENU_MAIN = 0;
	private final int ID_ACTION_SAVE = OPTIONMENU_MENU_MAIN + 1;
	private final int ID_ACTION_DOWNLOAD = ID_ACTION_SAVE + 1;

	private final short ORDER_POS_FIRST = 1;
	private final short ORDER_POS_SECOND = ORDER_POS_FIRST + 1;
	private final short ORDER_POS_THIRD = ORDER_POS_SECOND + 1;

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		if (res == null)
			return false;
		try {
			if (menu != null) {
				menu.close();
				menu.clear();
			}

			SubMenu submenu = menu.addSubMenu(OPTIONMENU_MENU_MAIN,
					OPTIONMENU_MENU_MAIN, ORDER_POS_THIRD/* Menu.NONE */,
					res.getString(R.string.main_tab_hint_btn_menu));

			menu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_SAVE, ORDER_POS_FIRST, "")
					.setIcon(R.drawable.content_save)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

			submenu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_DOWNLOAD, Menu.NONE,
					res.getString(R.string.str_vattu_download))
					.setIcon(R.drawable.download_icon)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);

			MenuItem menuItem = submenu.getItem();
			menuItem.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
			menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	@Override
	public void onBackPressed() {

		if (checkDataChanged()) {
			// show dialog to alert users
			showDialogOK();
		} else {
			finish();
		}
	}

	private boolean checkDataChanged() {

		ArrayList<VattuModel> itemList = dataAdapter.getItemList();

		boolean hasChanged = false;

		for (int i = 0; i < itemList.size(); i++) {
			if (itemList.get(i).hasChanged() == true) {
				hasChanged = true;
				break;
			}
		}

		return hasChanged;
	}

	private Boolean isShowDialog = false;
	public Dialog dialog;
	public Button btnSave;
	public Button btnCancel;

	private void showUnsavedDataDialog() {
		if (!isShowDialog) {
			isShowDialog = true;
			// imgSet = _imgSet;
			dialog = new Dialog(DanhMucVatTuActivity.this);
			dialog.getWindow();
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_unsave);
			dialog.getWindow().setBackgroundDrawable(
					new ColorDrawable(android.graphics.Color.TRANSPARENT));

			this.btnSave = (Button) dialog.findViewById(R.id.btnSave);
			this.btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
			btnSave.setOnClickListener(this);
			btnCancel.setOnClickListener(this);

			dialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					isShowDialog = false;
				}
			});

			dialog.show();
		}

	}

	private void showDialogOK() {
		Dialog dialog = null;
		ConfirmDialog.ConfirmBuilder customBuilder = new ConfirmDialog.ConfirmBuilder(
				DanhMucVatTuActivity.this);
		String msg = res.getString(R.string.str_unsaved_data_waring);

		customBuilder
				.setTitle(res.getString(R.string.str_thongBao))
				.setMessage(msg)
				.setNegativeButton(res.getString(R.string.str_no),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (dialog != null)
									dialog.dismiss();
								if (DanhMucVatTuActivity.this != null) {
									finish();
								}
							}
						})
				.setPositiveButton(res.getString(R.string.str_yes),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (dialog != null)
									dialog.dismiss();
								if (DanhMucVatTuActivity.this != null) {
									saveDanhMucVatTu();
									finish();
								}
							}
						});
		dialog = customBuilder.create();

		if (dialog != null)
			dialog.show();
	}

	private void saveDanhMucVatTu() {
		VatTuDataSource vt = new VatTuDataSource();
		for (int i = 0; i < listvattuModel.size(); i++) {
			VattuModel vattu = listvattuModel.get(i);
			if (vattu.hasChanged()) {
				vt.updateStatus(vattu);
				vattu.setHasChanged(false);
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (v == btnSave) {
			saveDanhMucVatTu();
			dialog.dismiss();
			finish();
		}
		if (v == btnCancel) {
			dialog.dismiss();
			finish();
		}

	}

	
	private ProgressDialog progressBar ;
	
	private void getDanhMucVatTu() {

		try {	
			
			progressBar = new ProgressDialog(this);
			progressBar.setMessage(res.getString(R.string.str_vattu_download_waiting));
			progressBar.setIndeterminate(true);
			progressBar.setCancelable(false);
			progressBar.show();
	
			RsGetDanhMucVatTuCountTask task = new RsGetDanhMucVatTuCountTask();
			task.execute();

		} catch (Exception e) {
			e.printStackTrace();

		}

	}


	private String pageCountResponse = "";
	private int itemCount = 0;

	private class RsGetDanhMucVatTuCountTask extends
			AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {		

			
			RsGetClient jParser = new RsGetClient();
			// http://192.168.1.46:46685
			String baseUrl = MainApplication.getServerURL();
			String url = baseUrl + "/ctrs/resources/danhmucvattu/"
					+ MainApplication.getMaDonViQuanLy();

			pageCountResponse = jParser.getValueFromUrl(url);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
		
			if (!pageCountResponse.isEmpty())
				itemCount = Integer.parseInt(pageCountResponse.trim());

			int pageCount = itemCount / 50;

			if (itemCount % 50 > 0)
				pageCount++;

			newVatTuList.clear();
			
			for (int i = 1; i < pageCount + 1; i++) {

				RsGetDanhMucVatTuTask task = new RsGetDanhMucVatTuTask();
				task.execute(i + "");

			}			
			
		}
		
		
		@Override
        protected void onPreExecute() {
		
        	
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
            //Log.i(TAG, "onProgressInsert");
        	
        	
        }

	}

	JSONArray messages = null;
	JSONObject json = null;
	ArrayList<HashMap<String, String>> messageList = null;

	private class RsGetDanhMucVatTuTask extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {

			RsGetClient jParser = new RsGetClient();
			// http://192.168.1.46:46685
			String baseUrl = MainApplication.getServerURL();
			String url = baseUrl + "/ctrs/resources/danhmucvattu/"
					+ MainApplication.getMaDonViQuanLy() + "/" + params[0];

			messages = jParser.getJSONFromUrl(url);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			addDanhMucVatTu();

		}

	}

	private List<VattuModel> newVatTuList = new ArrayList<VattuModel>();

	protected void addDanhMucVatTu() {

		try {

			int j = 1;
			// looping through All Contacts
			for (int i = 0; i < messages.length(); i++) {

				JSONObject c = messages.getJSONObject(i);

				VattuModel vt = new VattuModel();

				vt.setMaVattu(c.getString("maVattu"));
				vt.setTenVattu(c.getString("tenVattu"));
				vt.setMaDVIQLY(c.getString("maDviqly"));
				vt.setDonGia(c.getDouble("donGia"));
				vt.setQuyCach(c.getString("quyCach"));
				vt.setSuDung(false);

				newVatTuList.add(vt);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		if(newVatTuList.size() ==itemCount) {
			storeDanhMucVatTu(newVatTuList);
		}
		
		
		//progressBar.setProgress(newVatTuList.size());
		 
		Log.i("Update Vat tu", newVatTuList.size() + "");
	}

	protected void storeDanhMucVatTu(List<VattuModel> newVatTuList) {

		VatTuDataSource dataSource = new VatTuDataSource();

		int j = 1;
		// looping through All Contacts
		for (int i = 0; i < newVatTuList.size(); i++) {

			VattuModel vt = newVatTuList.get(i);

			boolean existed = false;

			existed = dataSource.checkVatTuExist(vt.getMaVattu(),
					vt.getMaDVIQLY());

			if (!existed) {

				long id = dataSource.insert(vt);
			} else {
				dataSource.update(vt);
				Log.i("Update Vat tu", i + "");
			}

		}
		        
		progressBar.dismiss();
		
		loadVattu();

		Toast.makeText(MainApplication.getAppContext(),
				res.getString(R.string.str_vattu_download_finish),
				Toast.LENGTH_SHORT).show();

	}

}
